package mo.leetcode_top;

import java.util.*;

public class L350 {

    public int[] intersect(int[] nums1, int[] nums2) {
        Map<Integer, Integer> key2values = new HashMap<>();
        for (int num : nums1) {
            Integer value = key2values.get(num);
            if (value == null) {
                value = 1;
            } else {
                value++;
            }
            key2values.put(num, value);
        }
        List<Integer> res = new ArrayList<>();
        for (int num : nums2) {
            Integer value = key2values.get(num);
            if (value == null || value <= 0) {
                continue;
            } else {
                res.add(num);
                value--;
                key2values.put(num, value);
            }
        }
        return res.stream().mapToInt(Integer::intValue).toArray();
    }

}
